import {EventSourcePolyfill} from "@/utils/eventsource.min.js";
import {getAccessToken, getTenantId} from '@/utils/auth'

const ss = void function createSSE(url) {
  if (window.EventSource) {
    // 根据环境的不同，变更url
    const baseURL = process.env.VUE_APP_BASE_API + '/admin-api/'
    // const url = process.env.VUE_APP_MSG_SERVER_URL
    var evtSource = new EventSource(baseURL + url);
    // var eventSource = new EventSourcePolyfill(
    //     baseURL + url,
    //    {
    //         // 设置重连时间
    //         heartbeatTimeout: 60 * 60 * 1000,
    //         // 添加token
    // headers: {
    //     'Content-Type': 'application/json;charset=utf-8',
    //     'Authorization': 'Bearer ' + getAccessToken(),
    //     'tenant-id':getTenantId(),
    // },
    //     }
    // );
    eventSource.onopen = (e) => {
      console.log("已建立SSE连接~")
    }
    eventSource.onmessage = (e) => {
      console.log("已接受到消息:", e.data)
    }
    eventSource.onerror = (e) => {
      if (e.readyState == EventSource.CLOSED) {
        console.log("SSE连接关闭");
      } else if (this.eventSource.readyState == EventSource.CONNECTING) {
        console.log("SSE正在重连");
        //重新设置token
        this.eventSource.headers = {
          'Authorization': `Bearer ${getToken()}`
        };
      } else {
        console.log('error', e);
      }
    };
  } else {
    console.log("你的浏览器不支持SSE~")
  }
}


export default ss
